package boerse.main.StockPriceProvider;

import boerse.main.Asset.Share;
import boerse.main.Exceptions.NoSuchShareException;

import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;

/**
 * the abstract definiton of the StockPriceProvider
 * @author Domi
 *
 */
public abstract class StockPriceProvider implements StockPriceInfo {

	protected Hashtable<String, Share> allShare;
    protected Timer timer;
	
	public StockPriceProvider() {
		super();
        timer = MyTimer.getTimer();
        this.allShare = new Hashtable<String, Share>();
	}
	
	/**
	 * return true if the given share is listed
	 */
	@Override
	public boolean isShareListed(String shareName) {
		try {
			searchShare(shareName);
			return true;
		} catch (NoSuchShareException e) {
			return false;
		}
		
	}

	/**
	 * get Timer ins
	 */
    public Timer getTime() {
        return timer;
    }

	@Override
	public long getCurrentShareRate(String shareName) {
		
		return searchShare(shareName).getPrice();
	}

	@Override
	public Share[] getAllShares() {
		
		Object[] o = allShare.values().toArray();
		Share[] allShareCopy = new Share[o.length];
		
		for (int i = 0; i < o.length; i++) {
			allShareCopy[i] = (Share) o[i];
		}
			
		return allShareCopy;
	}
	
	public Share getShare(String shareName) {
		
		return searchShare(shareName);
	}
	
	public void updateShareRates() {
		for (Share s : allShare.values()) {
			updateShareRate(s);
		}
	}
	
	protected abstract void updateShareRate(Share share);
	
	protected void startUpdate() {
		timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                updateShareRates();
            }
        }  , 1000, 2000);
    }


	private Share searchShare(String shareName) {
		Share share = allShare.get(shareName);	
		if (share == null)
			throw new NoSuchShareException("No such share");
		return share;
	}
	
	public void addShare(Share share) {
		allShare.put(share.getName(), share);
	}
	
	public void addShare(Share[] share) {
		for (Share s : share) {
			allShare.put(s.getName(), s);
		}
	}

}
